<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\KeywordRequest;
use App\Models\Keyword;
use App\Repository\KeywordRepository;
use Illuminate\Http\Request;

class KeywordsController extends Controller
{
    private $keywordRepository;
    private $keyword;
    public function __construct(KeywordRepository $keywordRepository,KeyWord $keyword)
    {
        $this->keywordRepository = $keywordRepository;
        $this->keyword = $keyword;

    }
    /**
     * 关键字首页
     *
     * @param Request $request
     * @return void
     */
    public function index(Request $request)
    {
        if($request->ajax()){
            //获取相关信息
             //获取信息
             $list = $this->keywordRepository->getList($request->input());
             return $this->tableAjax($list);
        }else{
            return view('admin.keywords.index');
        }

    }

    /**
     * 添加页面
     *
     * @return void
     */
    public function create()
    {
        return view('admin.keywords.create_and_edit');
    }

    public function edit(KeywordRequest $request,$id)
    {
        $data = $this->keyword::find($id);
        
        return view('admin.keywords.create_and_edit',['info'=>$data]);
    }

    /**
     * @param KeywordRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destory(KeywordRequest $request)
    {
        if($this->keyword::destroy($request->id)){
            return $this->success('删除成功');
        }else{
            return $this->error('删除失败');
        }
    }

    /**
     * 添加方法
     */
    public function store(KeywordRequest $request)
    {
        //保存数据
        $keyword = new Keyword();
        $keyword -> keyword = $request -> keyword;
        $keyword -> is_show = $request -> is_show ?:0;

        if ($keyword -> save()){
            return $this->success('添加成功');
        }else{
            return $this -> error('添加失败');
        }

    }

    public function update(KeywordRequest $request)
    {
        $keyword = $this->keyword::find($request->id);
        $keyword ->keyword = $request -> keyword;
        $keyword -> is_show = $request -> is_show ?:0;
        if ($keyword -> save()){
            return $this->success('更新成功');
        }else{
            return $this -> error('更新失败');
        }  
    }
}
